package com.ruoyi.stream.server.handler;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.stream.framework.constans.StreamProtocolConstants;
import com.ruoyi.stream.framework.core.protocol.StreamAliveRequest;
import com.ruoyi.stream.framework.core.protocol.StreamAliveResponse;
import com.ruoyi.stream.framework.enums.SKAResponseOption;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.Arrays;
import java.util.List;

public class SKARequestDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        try {
            byte[] magic = new byte[StreamProtocolConstants.SKA_REQ_MAGIC.length];
            byteBuf.readBytes(magic);
            if (!Arrays.equals(magic, StreamProtocolConstants.SKA_REQ_MAGIC)) {
                return;
            }
            long length = byteBuf.readLong();
            byte[] full = new byte[(int) length];
            byteBuf.readBytes(full);
            StreamAliveRequest to = JSON.parseObject(full).to(StreamAliveRequest.class);
            list.add(to);
        }catch (Exception e){
            e.printStackTrace();
            StreamAliveResponse response = new StreamAliveResponse();
            response.setResponseOption(SKAResponseOption.REFUSE);
            response.setBody(e.getLocalizedMessage());
            channelHandlerContext.writeAndFlush(response);
        }

    }
}
